import { Component, Input, OnInit, ViewChild, OnChanges, SimpleChanges , ElementRef, ViewEncapsulation} from '@angular/core';
import { FormBuilder, FormControl, FormGroup, Validators ,ValidationErrors } from "@angular/forms";
import { NzMessageService } from "ng-zorro-antd";
import { Observable, Observer } from 'rxjs';
import { FcsService } from "../../../../../service/fcs.service";
import { CommonService } from "../../../../../service/common.service";
import { randomBytes } from 'crypto';

@Component({
  selector: 'app-alias-delete',
  encapsulation: ViewEncapsulation.None,
  templateUrl: './alias-delete.component.html',
  styleUrls: ['./alias-delete.component.less']
})

export class AliasDeleteComponent implements OnInit {
  @ViewChild('deleteAliasFormComponent', { static: true }) deleteAliasFormComponent;
  deleteAliasForm: FormGroup;
  @ViewChild('aliasesEle', { static: false }) aliasesEle?: ElementRef;
  @Input() groupId:string = "";
  @Input() funcId:string = "";
  aliasId:string;
  aliasList = [];
  isLoading:boolean = false;
  constructor(
  private fb: FormBuilder,
  private commonService: CommonService,
  private fcsService: FcsService,
  private msgService: NzMessageService
  ) {
    this.deleteAliasForm = this.fb.group({
      alias: ['', [Validators.required]]
    });
  }

  ngOnInit() {
    // 添加时间戳和随机数字段
    this.deleteAliasForm.addControl('timestamp', new FormControl(Date.now()));
    this.deleteAliasForm.addControl('nonce', new FormControl(randomBytes(5).toString(36).substring(0, 9)));

    this.getAliasList();
  }

  async getAliasList(){
    this.isLoading = true;
    let aliasRes = await this.commonService.getAliasList(this.fcsService,this.groupId,this.funcId);
    this.isLoading = false;
    if(aliasRes && aliasRes['success']){
      this.aliasList = aliasRes['alias']
    }
  }

  aliasChange(value:string){
    if(value && value != ""){
      this.aliasId = value;
    }
  }

  submit():Promise<boolean>{
    let group = this.deleteAliasForm as FormGroup;
    for (const i in group.controls) {
      if (i) {
          group.controls[i].markAsDirty();
          group.controls[i].updateValueAndValidity();
      }
    }
    return new Promise((resolve, reject) => {
     if (!group['valid']) {
        resolve(false);
     } else {
       let aliasName = this.aliasList.filter(item => item.aliasId === this.aliasId)[0].aliasName;
       this.fcsService.deleteFunctionAlias(this.groupId,this.funcId,aliasName).subscribe(res => {
          this.msgService.success('别名删除成功！');
          resolve(true);
        },err => {
          resolve(false);
        })
     }
    });
  }

}
